package com.doubao.common.mq.producer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class RocketMQProducer implements MessageProducer {

    private final RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendMessage(String topic, Object message) {
        try {
            log.info("发送消息到主题 {}: {}", topic, message);
            rocketMQTemplate.convertAndSend(topic, message);
        } catch (Exception e) {
            log.error("发送消息失败: topic={}, message={}", topic, message, e);
            throw e;
        }
    }

    @Override
    public void sendMessage(String topic, String tags, Object message) {
        try {
            String destination = topic + ":" + tags;
            log.info("发送带标签消息: destination={}, message={}", destination, message);
            rocketMQTemplate.convertAndSend(destination, message);
        } catch (Exception e) {
            log.error("发送带标签消息失败: topic={}, tags={}, message={}", topic, tags, message, e);
            throw e;
        }
    }

    @Override
    public void sendDelayedMessage(String topic, Object message, int delayLevel) {
        try {
            log.info("发送延迟消息: topic={}, delayLevel={}, message={}", topic, delayLevel, message);
            rocketMQTemplate.syncSend(topic,
                    MessageBuilder.withPayload(message)
                            .setHeader("DELAY", delayLevel)
                            .build(),
                    3000);
        } catch (Exception e) {
            log.error("发送延迟消息失败: topic={}, delayLevel={}, message={}", topic, delayLevel, message, e);
            throw e;
        }
    }
}